#!/usr/bin/env python
# Author: Derek Green

PKG = 'nltk_parser'

import roslib; roslib.load_manifest(PKG)
import rospy
import re
from nltk_parser.srv import *

# interprets an Nltk parse tree for WubbleWorld commands
class NltkWWInterpreter():
    def __init__(self):
        rospy.init_node('ntlk_ww_interpreter_service', anonymous=True)
        self.service = rospy.Service('nltk_ww_interpret', WWParseInterpretation, self.handle_interpret_request)
        rospy.wait_for_service('nltk_parse')
        try:
            self.parse_nltk = rospy.ServiceProxy('nltk_parse', Parse)
        except rospy.ServiceException, e:
            print "ntlk_parse Failed: %s"%e

    def handle_interpret_request(self, request):
        command = ""
        size = ""
        color = ""
        shape = ""
        try:
            print "Nltk WW Interpreter processing string: " + request.sentence
            parse_tree = self.parse_nltk(request.sentence).parse_tree.replace("\n","")
            if re.search("COMMAND", parse_tree):
                command = re.search("\(V (\w+)\)", parse_tree)
                command = "" if command == None else command.group(1)
                size = re.search("\(SIZE (\w+)\)", parse_tree)
                size = "" if size == None else size.group(1)
                color = re.search("\(COLOR (\w+)\)", parse_tree)
                color = "" if color == None else color.group(1)
                shape = re.search("\(SHAPE (\w+)\)", parse_tree)
                shape = "" if shape == None else shape.group(1)
                print "parse_tree = ", parse_tree
            elif re.search("YESNO", parse_tree):
                command = re.search("\(YESNO (\w+)\)", parse_tree)
                command = "" if command == None else command.group(1)
            else:
                rospy.logdebug("nltk_ww_interpreter.py has issues.")

        except rospy.ServiceException, e:
            print "Ntlk WW Interpreter failed: %s"%e
        return [command, size, color, shape]

if __name__ == '__main__':
    try:
        n = NltkWWInterpreter()
        rospy.spin()
    except rospy.ROSInterruptException: pass

